<template>
  <el-select
    v-model="selectId"
    placeholder="请选择"
    :props="defaultProps"
    :data="props.data?props.data:selectData"
  >
    <el-option
      v-for="item in selectData"
      :key="item.id"
      :label="item.name"
      :value="item.id">
    </el-option>
  </el-select>
</template>

<script lang='ts' setup>
import {
  getCurrentInstance, ref, onMounted, defineProps, computed, withDefaults,
} from 'vue';

const { proxy } = getCurrentInstance();

// 定义接收父组件的值
interface Props {
  modelValue?: any
  url?: string
  data?: any[]
}

const props = withDefaults(defineProps<Props>(), {
  modelValue: () => null,
});

const defaultProps = { // 下拉菜单显示标签对应的属性名
  value: 'id',
  label: 'name',
};

const selectData = ref();
const getSelectData = async () => {
  const resData:any = await new proxy.$Request(props.url).get();
  if (resData.success) {
    selectData.value = resData.data;
  }
};

if (props.data == null) {
  onMounted(getSelectData);
} else {
  selectData.value = [];
}

const selectId = ref(computed({
  get() {
    return props.modelValue;
  },
  set(val) {
    proxy.$emit('update:modelValue', val);
  },
}));

</script>

<style scoped>

</style>
